// 轮播图管理API服务 - 支持MongoDB
const express = require('express');
const router = express.Router();
const { authenticateToken } = require('../middleware/auth');
const Authorization = require('../middleware/authorization');
const { getMongoDB } = require('../config/multi-database');

// 获取轮播图列表
router.get('/carousel', async (req, res) => {
    try {
        const { 
            page = 1, 
            limit = 20, 
            isActive = true 
        } = req.query;

        const db = getMongoDB();
        const skip = (page - 1) * limit;
        
        // 构建查询条件
        const query = {};
        if (isActive !== undefined) query.isActive = isActive === 'true';
        
        // 获取总数
        const total = await db.collection('carousel').countDocuments(query);
        
        // 获取数据
        const cursor = db.collection('carousel')
            .find(query)
            .sort({ sortOrder: 1, createdAt: -1 })
            .skip(skip)
            .limit(parseInt(limit));
        
        const data = await cursor.toArray();
        
        res.json({
            success: true,
            data: data,
            pagination: {
                page: parseInt(page),
                limit: parseInt(limit),
                total,
                totalPages: Math.ceil(total / limit)
            }
        });
    } catch (error) {
        console.error('获取轮播图列表失败:', error);
        res.status(500).json({
            success: false,
            message: '获取轮播图列表失败'
        });
    }
});

// 获取启用的轮播图（前端使用）
router.get('/carousel/active', async (req, res) => {
    try {
        const { limit = 10 } = req.query;

        const db = getMongoDB();
        
        const cursor = db.collection('carousel')
            .find({ isActive: true })
            .sort({ sortOrder: 1, createdAt: -1 })
            .limit(parseInt(limit));
        
        const data = await cursor.toArray();
        
        res.json({
            success: true,
            data: data
        });
    } catch (error) {
        console.error('获取启用的轮播图失败:', error);
        res.status(500).json({
            success: false,
            message: '获取启用的轮播图失败'
        });
    }
});

// 获取轮播图详情
router.get('/carousel/:id', authenticateToken, async (req, res) => {
    try {
        const db = getMongoDB();
        const { ObjectId } = require('mongodb');
        
        const carousel = await db.collection('carousel').findOne({ 
            _id: new ObjectId(req.params.id) 
        });
        
        if (!carousel) {
            return res.status(404).json({
                success: false,
                message: '轮播图不存在'
            });
        }

        res.json({
            success: true,
            data: carousel
        });
    } catch (error) {
        console.error('获取轮播图详情失败:', error);
        res.status(500).json({
            success: false,
            message: '获取轮播图详情失败'
        });
    }
});

// 创建轮播图
router.post('/carousel', authenticateToken, Authorization.requireRole(['admin', 'editor']), async (req, res) => {
    try {
        const db = getMongoDB();
        const carouselData = {
            ...req.body,
            createdBy: req.user.userId,
            createdAt: new Date(),
            updatedAt: new Date()
        };

        // 验证必填字段
        if (!carouselData.name || !carouselData.imageUrl) {
            return res.status(400).json({
                success: false,
                message: '轮播图名称和URL为必填项'
            });
        }

        // 设置默认值
        if (!carouselData.sortOrder) carouselData.sortOrder = 0;
        if (carouselData.isActive === undefined) carouselData.isActive = true;

        const result = await db.collection('carousel').insertOne(carouselData);
        const carousel = { ...carouselData, _id: result.insertedId };

        res.status(201).json({
            success: true,
            message: '轮播图创建成功',
            data: carousel
        });
    } catch (error) {
        console.error('创建轮播图失败:', error);
        res.status(500).json({
            success: false,
            message: '创建轮播图失败'
        });
    }
});

// 更新轮播图
router.put('/carousel/:id', authenticateToken, Authorization.requireRole(['admin', 'editor']), async (req, res) => {
    try {
        const db = getMongoDB();
        const { ObjectId } = require('mongodb');
        
        const carousel = await db.collection('carousel').findOne({ 
            _id: new ObjectId(req.params.id) 
        });
        
        if (!carousel) {
            return res.status(404).json({
                success: false,
                message: '轮播图不存在'
            });
        }

        const updateData = {
            ...req.body,
            updatedAt: new Date()
        };

        const result = await db.collection('carousel').findOneAndUpdate(
            { _id: new ObjectId(req.params.id) },
            { $set: updateData },
            { returnDocument: 'after' }
        );

        res.json({
            success: true,
            message: '轮播图更新成功',
            data: result.value
        });
    } catch (error) {
        console.error('更新轮播图失败:', error);
        res.status(500).json({
            success: false,
            message: '更新轮播图失败'
        });
    }
});

// 删除轮播图
router.delete('/carousel/:id', authenticateToken, Authorization.requireRole(['admin', 'editor']), async (req, res) => {
    try {
        const db = getMongoDB();
        const { ObjectId } = require('mongodb');
        
        const carousel = await db.collection('carousel').findOne({ 
            _id: new ObjectId(req.params.id) 
        });
        
        if (!carousel) {
            return res.status(404).json({
                success: false,
                message: '轮播图不存在'
            });
        }

        const result = await db.collection('carousel').deleteOne({ 
            _id: new ObjectId(req.params.id) 
        });

        if (result.deletedCount > 0) {
            res.json({
                success: true,
                message: '轮播图删除成功'
            });
        } else {
            res.status(500).json({
                success: false,
                message: '轮播图删除失败'
            });
        }
    } catch (error) {
        console.error('删除轮播图失败:', error);
        res.status(500).json({
            success: false,
            message: '删除轮播图失败'
        });
    }
});

// 批量更新轮播图排序
router.post('/carousel/sort', authenticateToken, Authorization.requireRole(['admin', 'editor']), async (req, res) => {
    try {
        const { sortData } = req.body;
        const db = getMongoDB();
        const { ObjectId } = require('mongodb');

        if (!Array.isArray(sortData) || sortData.length === 0) {
            return res.status(400).json({
                success: false,
                message: '排序数据无效'
            });
        }

        const session = db.client.startSession();
        
        try {
            session.startTransaction();
            
            for (const item of sortData) {
                await db.collection('carousel').updateOne(
                    { _id: new ObjectId(item.id) },
                    { $set: { sortOrder: item.sortOrder, updatedAt: new Date() } },
                    { session }
                );
            }
            
            await session.commitTransaction();
            
            res.json({
                success: true,
                message: '轮播图排序更新成功'
            });
        } catch (error) {
            await session.abortTransaction();
            throw error;
        } finally {
            await session.endSession();
        }
    } catch (error) {
        console.error('批量更新轮播图排序失败:', error);
        res.status(500).json({
            success: false,
            message: '批量更新轮播图排序失败'
        });
    }
});

// 切换轮播图状态
router.patch('/carousel/:id/toggle', authenticateToken, Authorization.requireRole(['admin', 'editor']), async (req, res) => {
    try {
        const db = getMongoDB();
        const { ObjectId } = require('mongodb');
        
        const carousel = await db.collection('carousel').findOne({ 
            _id: new ObjectId(req.params.id) 
        });
        
        if (!carousel) {
            return res.status(404).json({
                success: false,
                message: '轮播图不存在'
            });
        }

        const newStatus = !carousel.isActive;
        
        const result = await db.collection('carousel').findOneAndUpdate(
            { _id: new ObjectId(req.params.id) },
            { $set: { isActive: newStatus, updatedAt: new Date() } },
            { returnDocument: 'after' }
        );

        res.json({
            success: true,
            message: `轮播图已${newStatus ? '启用' : '禁用'}`,
            data: result.value
        });
    } catch (error) {
        console.error('切换轮播图状态失败:', error);
        res.status(500).json({
            success: false,
            message: '切换轮播图状态失败'
        });
    }
});

module.exports = router;